import React, { Component } from 'react';
import { Table } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { CONST_DATE_FORMAT } from '@/constants';
import styles from '../index.less';

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      constants: {
        // titles: [{ 'id': 19, 'title_type': { 'id': 60, 'type_name': '领导', 'postscript': '', 'state': 1 }, 'title_name': 'A头衔', 'title_state': 1 }, { 'id': 20, 'title_type': { 'id': 61, 'type_name': '值班员', 'postscript': '', 'state': 1 }, 'title_name': 'B头衔', 'title_state': 1 }, { 'id': 21, 'title_type': { 'id': 62, 'type_name': '驾驶员', 'postscript': '', 'state': 1 }, 'title_name': 'C头衔', 'title_state': 0 }],
        // shifts: [{ 'id': 25, 'shift_name': '白班', 'start_date': '09:00', 'end_date': '18:00' }, { 'id': 26, 'shift_name': '夜班', 'start_date': '18:00', 'end_date': '09:00' }, { 'id': 27, 'shift_name': '全日班', 'start_date': '09:00', 'end_date': '09:00' }]
        titles: [],
        shifts: []
      }
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'title/queryData',
      payload: {
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, titles: data } });
        }
      }
    });
    this.props.dispatch({
      type: 'shift/queryData',
      payload: {
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, shifts: data } });
        }
      }
    });
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState);
  }

  generateColumns = (titles, shifts, data = {}) => {
    const columns = [
      {
        title: '日期',
        dataIndex: 'date',
        align: 'center',
        ellipsis: true,
        width: 180,
        render: (text, record) => {
          const { date, week } = record;

          return (
            <div style={{ color: 'rgb(43, 151, 239)', textAlign: 'center' }}>
              <div>{date}</div>
              <div>{week}</div>
            </div>
          );
        }
      }
    ];

    if (titles && titles.length > 0) {
      titles.forEach(item => {
        columns.push({
          title: item.title_name,
          dataIndex: item.id,
          align: 'center',
          ellipsis: true,
          children: shifts.map(shift => {
            const { shift_name, start_date, end_date } = shift;

            return {
              title: <div><div>{shift_name}</div><div>{`${start_date}~${start_date < end_date ? `` : `次日`}${end_date}`}</div></div>,
              dataIndex: `${item.id}_${shift.id}`,
              align: 'center',
              ellipsis: true,
              width: 180,
              render: (text, record) => {
                const arrange = data[record.date] || {};
                const dutyShift = arrange[shift.id] || {};
                const { children = [] } = dutyShift;

                if (children && children.length > 0) {
                  const filter = children.filter(child => child.shift_id === shift.id && child.title_id === item.id);

                  if (filter && filter[0]) {
                    const { name, mobile } = filter[0];

                    return (
                      <div style={{ textAlign: 'center' }}>
                        <div>
                          {name}
                        </div>
                        <div>{mobile}</div>
                      </div>
                    );
                  }
                }
              },
              onCell: (record, index) => {
                return {
                  onClick: () => {
                    if (typeof this.props.onSelect === 'function') {
                      this.props.onSelect(data[record.date], moment(record.date, CONST_DATE_FORMAT));
                    }
                  }
                }
              }
            }
          }),
        });
      });

      return columns;
    }

    return [...columns, { title: '', dataIndex: 'empty_01' }, { title: '', dataIndex: 'empty_02' }, { title: '', dataIndex: 'empty_03' }]
  }

  generateData = (time) => {
    const startTime = moment(time).startOf('month');
    const days = startTime.daysInMonth();
    const result = [];

    for (let i = 0; i < days; i++) {
      const date = moment(startTime).add(i, 'days');

      result.push({
        id: i,
        date: date.format(CONST_DATE_FORMAT),
        week: this.getWeek(date.day())
      });
    }

    return result;
  }

  getWeek = (data) => {
    switch (data) {
      case 0: return '星期日';
      case 1: return '星期一';
      case 2: return '星期二';
      case 3: return '星期三';
      case 4: return '星期四';
      case 5: return '星期五';
      case 6: return '星期六';
    }
  }

  render() {
    const { constants = {} } = this.state;
    const { loading, modularName, data = {}, time } = this.props;
    const { titles = [], shifts = [] } = constants;

    return (
      <div className={styles.table_wrapper} style={{ padding: '12px 16px' }}>
        <Table
          bordered
          columns={this.generateColumns(titles, shifts, data)}
          dataSource={this.generateData(time)}
          loading={!!loading.effects[`${modularName}/queryData`] || !!loading.effects[`title/queryData`] || !!loading.effects[`shift/queryData`]}
          pagination={false}
          rowKey='id'
          scroll={{ x: true, y: 640, scrollToFirstRowOnChange: true }}
        />
      </div>
    );
  }
}